<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <!-- 用户id、ip、登录时间、地区、状态 -->
            <a-col :md="8" :sm="24">
              <a-form-item label="用户标识">
                <a-input v-model="queryParam.identify" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="客服">
                <AWM-select 
                  v-model="queryParam.adminId"
                  placeholder="请选择客服"
                  funStr="adminByNoAuth"
                ></AWM-select>
                <!-- <a-input v-model="queryParam.identify" placeholder="" />
                 -->
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="发送时间">
                <a-range-picker
                  show-time
                  v-model="queryParam.buildTime"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  :placeholder="['请选择开始日期', '请选择结束日期']"
                />
              </a-form-item>
            </a-col>

            <!-- <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select v-model="queryParam.status" placeholder="请选择">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option v-for="it in statusList" :key="it.id" :value="it.id">{{ it.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col> -->
            <!-- <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="状态">
                  <a-select v-model="queryParam.status" placeholder="请选择">
                    <a-select-option v-for="it in statusList" :key="it.id" :value="it.id">{{it.name}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template> -->
            <!-- <a-col :md="(!advanced && 8) || 24" :sm="24"> -->
            <a-col :md="8" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- <a-button type="primary" icon="plus" @click="handleDeleteCu">点击</a-button> -->
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
        :scroll="{ x: 'auto' }"
      >
        <span slot="contentType" slot-scope="text">
          <a-badge
            :color="text | statusFilter(contentTypeList, 'status')"
            :text="text | statusFilter(contentTypeList, 'name')"
          />
        </span>
        <span slot="fromType" slot-scope="text">
          <a-badge
            :color="text | statusFilter(fromTypeList, 'status')"
            :text="text | statusFilter(fromTypeList, 'name')"
          />
        </span>
        <span slot="param" slot-scope="text">
          <div class="remark-wrap">{{ text }}</div>
        </span>
        <span slot="identity" slot-scope="text, scope">
          <a-tooltip v-if="text.length > 12">
            <template slot="title">
              {{ text }}
            </template>
            <span @click="handleCopy(text)" class="talk-wrap" :class="{'server-talk': scope.fromType == 1}">
              <span class="talk-user"
                ><a-tag color="#108ee9">{{ scope.userIDentity }}</a-tag></span
              >
              <span class="talk-to">&nbsp;=>&nbsp;</span>
              <span class="talk-admin"
                ><a-tag color="#52c41a">{{ scope.adminName || '系统' }}</a-tag></span
              >
            </span>
          </a-tooltip>
          <div class="remark-wrap" v-else @click="handleCopy(text)">{{ text }}</div>
        </span>
        <span slot="content" slot-scope="text, scope">
          <div class="ellipsis2" :title="text" v-if="scope.contentType == 1">
            {{
               text
            }}
          </div>
          <div class="ellipsis2" v-if="scope.contentType == 0">
            {{
              `${scope.adminName} 为你服务`
            }}
          </div>
          <div :title="text" v-if="scope.contentType == 2">
            <!-- {{text}} -->
            <img class="service-img" :src="`${baseUrl}/${text}`" alt="" v-if="differentFile(text) == 'img'" @click="handleImg(text)">
            <div class="service-file" alt="" v-else>
              {{text.substr(0,5)}}... <a-button type="link" @click="handleDown(text)">下载</a-button>
            </div>
          </div>
          </span>
      </s-table>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { mapGetters } from 'vuex'
import { STable, Ellipsis } from '@/components'
import AWMSelect from '@/components/AWMSelect'
import { serviceLogList } from '@/api/service'
import { statusList, eachMap } from '@/utils/other'
const columns = [
  // {
  //   title: 'ID',
  //   dataIndex: 'id',
  //   key: 'id',
  //   width: 100,
  // },
  {
    title: '对象',
    dataIndex: 'identity',
    width: 150,
    scopedSlots: { customRender: 'identity' },
  },
  {
    title: '内容',
    dataIndex: 'content',
    width: 300,
    scopedSlots: { customRender: 'content' },
  },
  {
    title: '消息内容类型',
    dataIndex: 'contentType',
    width: 150,
    scopedSlots: { customRender: 'contentType' },
  },
  {
    title: '消息来源',
    dataIndex: 'fromType',
    width: 150,
    scopedSlots: { customRender: 'fromType' },
  },
  {
    title: '发送时间',
    dataIndex: 'addTime',
    key: 'addTime',
    width: 180,
  },
]
const contentTypeList = [
  {
    id: 0,
    status: '#909399',
    name: '分配',
  },
  {
    id: 1,
    status: '#87d068',
    name: '文本',
  },
  {
    id: 2,
    status: '#108ee9',
    name: '文件',
  },
]
const fromTypeList = [
  {
    id: 1,
    status: '#87d068',
    name: '客服',
  },
  {
    id: 2,
    status: '#108ee9',
    name: '用户',
  },
]

export default {
  name: 'AWM-userLoginList',
  components: {
    STable,
    Ellipsis,
    AWMSelect
  },
  data() {
    this.columns = columns
    return {
      contentTypeList,
      fromTypeList,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      parameter: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParam: {},
      data: [],
      // 状态
      statusList,
      // 排序
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let sortJ = this.sortJ
        if (parameter.sortField) {
          parameter.sortJ = sortJ
        }
        const requestParameters = Object.assign(parameter, this.queryParam)
        if (requestParameters.buildTime) {
          requestParameters.startTime = requestParameters.buildTime[0]
          requestParameters.endTime = requestParameters.buildTime[1]
          delete requestParameters.buildTime
        }
        return serviceLogList(requestParameters).then((res) => {
          let result = {
            data: res.data.data.map((v) => {
              v.identity = v.identity || ''
              v.userIDentity = `${v.identity.substr(0, 5)}...${v.identity.substr(-5)}`
              return v
            }),
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pages,
          }
          return result
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  created() {},
  computed: {
    ...mapGetters({'baseUrl': 'baseUrl'}),
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
  },
  methods: {
    handleImg(text){
      window.open(`${this.baseUrl}/${text}`)
    },
    handleDown(a_url){
      let url = `${this.baseUrl}/${a_url}`
      var xhr = new XMLHttpRequest();
			xhr.open('get', url, true); // 也可以使用POST方式，根据接口
			// 						xhr.setRequestHeader("dis_k",`cb9a62d3796e276f8707318b3c48ed3d`);
			// xhr.setRequestHeader("dis_t",`1617786336`);
			xhr.responseType = "blob"; // 返回类型blob

			xhr.onload = function () {
			  if (this.status === 200) {
				var blob = this.response;
				var reader = new FileReader();

				reader.readAsDataURL(blob); // 转换为base64，可以直接放入a表情href
				reader.onload = function (e) {
				  var a = document.createElement('a');
          let arr = url.split('/')
				  a.download = arr.pop() || ''; //下载文件名
				  a.href = e.target.result;	
				  a.click();
				  window.URL.revokeObjectURL(e.target.result)
				};
			  }
			}; 
			xhr.send();
    },
    differentFile(str){
      const arr = str.split('.')
      if(arr.length < 2) return 'unkonw'
      let last = arr.pop()
      if(['png', 'jpg'].indexOf(last) != -1){
        return 'img'
      }else{
        return 'other'
      }
    },
    handleCopy(data) {
      const url = data
      const oInput = document.createElement('input')
      oInput.value = url
      document.body.appendChild(oInput)
      oInput.select() // 选择对象;
      document.execCommand('Copy') // 执行浏览器复制命令
      oInput.remove()
      this.$message.success('复制成功')
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    saveCB() {
      const form = this.$refs.createModal.form
      this.visible = false
      this.confirmLoading = false
      // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.id > 0) {
            userUpdate(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('修改成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          } else {
            delete values.id
            userAdd(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('新增成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleDeleteCu() {
      this.columns.splice(1, 1)
      // this.table.key ++;
      this.$forceUpdate()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
    handleDel(a_record) {
      let self = this
      const modal = self.$confirm({
        title: '用户删除',
        content: `是否删除用户:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDeleteRole(a_record.id, modal, -1),
        onCancel: () => {},
      })
    },
    handleFreeze(a_record) {
      let self = this
      const modal = self.$confirm({
        title: '用户冻结',
        content: `是否冻结用户:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDeleteRole(a_record.id, modal, 2),
        onCancel: () => {},
      })
    },
    handleDeleteRole(a_id, a_modal, a_type) {
      return new Promise((resolve, reject) => {
        let data = { id: a_id, status: a_type }
        userUpdate(data)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.success('删除成功!')
            resolve()
          })
          .catch((err) => {
            a_modal.destroy()
            this.$message.error('操作失败!')
          })
      })
    },
  },
}
</script>
<style lang="less" scoped>
.ellipsis2 {
  width: 280px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.talk-wrap {
  width: 300px;
  display: flex;
  &.server-talk {
    .talk-user {
      order: 3;
    }
    .talk-admin {
      order: 1;
    }
  }
  .talk-user {
    order: 1;
  }
  .talk-to {
    order: 2;
    // font-size: 20px;
  }
  .talk-admin {
    order: 3;
  }
}
.service-img{
  max-width: 100px;
  max-height: 100px;
  cursor: pointer;
}
</style>

 